"use client";
import React, { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectGroup } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { toast } from "sonner";
import { createNewTeam } from '@/controller/team';
import { getUserTeam, createTeamMember, TeamMemberType } from '@/controller/team_members';
import { createProject } from "@/controller/project";
import { useRouter } from 'next/navigation';
import { getUser } from "@/controller/auth";
import { Loader2Icon } from 'lucide-react';
import { post } from '@/lib/request';
export function SearchForm() {
    const router = useRouter();
    const t = useTranslations('common');
    const [isSearching, setIsSearching] = useState(false);
    const [searchType, setSearchType] = useState<'creator' | 'posts'>('creator');
    const [resultCount, setResultCount] = useState<string>('25');
    const [query, setQuery] = useState('');
    const createNewProject = async (teamMember: TeamMemberType) => {
        if (!teamMember) {
            toast.error('Team member not found');
            setIsSearching(false);
            return;
        }
        const { data: projectData, error: projectDataError } = await createProject({
            name: query,
            content: query,
            team_id: teamMember.team_id,
            search_objective: searchType,
            search_conditions: { resultCount: parseInt(resultCount) },
        }, teamMember.user_id)
        if (!projectData || projectDataError) {
            toast.error('create project failed');
            setIsSearching(false);
            return;
        }
        await post('/tasks/create', {
            project_id: projectData.project_id,
            "task_type": "keyword_analysis_flow",
            "input_data": {
                "content": query
            }
        })
        // 导航到项目详情页
        router.push(`/project/${projectData.project_id}`);
        // get(`/createKeyword?projectId=${projectData.project_id}`);
    }
    const handleSearch = async (e: React.FormEvent) => {
        e.preventDefault();
        if (query.trim()) {
            setIsSearching(true);
            const user = await getUser()
            if (!user) {
                toast.error('User not found')
                return
            }
            const { data: teamMember, error: teamError } = await getUserTeam(user.id)
            if (!teamMember || teamError) {
                // 没有团队
                toast('You don\'t have a team yet, creating...')
                const { data: newTeam, error: newTeamError } = await createNewTeam(user.id, user.email || 'new team')
                if (!newTeam || newTeamError) {
                    toast.error('create team failed');
                    setIsSearching(false);
                    return;
                }
                const { data: teamMember, error: teamMemberError } = await createTeamMember({
                    team_id: newTeam.team_id,
                    user_id: user.id,
                    role: 'Owner',
                    email: user.email || 'new team',
                    status: 'active',
                    invited_by: user.id,
                    inviter: user.id
                })

                if (teamMemberError) {
                    toast.error('Team member creation failed');
                    setIsSearching(false);
                    return;
                } else {
                    toast.success('Team created successfully');
                }
                createNewProject(teamMember)
            } else {
                createNewProject(teamMember)
            }
        }
    };

    return (
        <div className={`w-full max-w-4xl ${isSearching ? 'opacity-70 pointer-events-none' : ''}`}>
            <form onSubmit={handleSearch} className="relative">
                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div className="relative mb-3">
                        <textarea
                            placeholder={t('placeholder')}
                            className="text-base w-full min-h-[100px] resize-none bg-transparent border-none outline-none shadow-none"
                            value={query}
                            onChange={(e) => setQuery(e.target.value)}
                            style={{ border: 'none', outline: 'none', boxShadow: 'none' }}
                        />
                    </div>

                    <div className="flex justify-between items-center">
                        <div className="flex space-x-3">
                            <Select value={searchType} onValueChange={(value) => setSearchType(value as 'creator' | 'posts')}>
                                <SelectTrigger className="w-[180px]">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectGroup>
                                        <SelectItem value="creator">{t('creator')}</SelectItem>
                                        <SelectItem value="posts">{t('posts')}</SelectItem>
                                    </SelectGroup>
                                </SelectContent>
                            </Select>

                            <Select value={resultCount} onValueChange={(value) => setResultCount(value)}>
                                <SelectTrigger className="w-[120px]">
                                    <SelectValue placeholder="Count" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectGroup>
                                        <SelectItem value="10">10 results</SelectItem>
                                        <SelectItem value="25">25 results</SelectItem>
                                        <SelectItem value="50">50 results</SelectItem>
                                        <SelectItem value="100">100 results</SelectItem>
                                    </SelectGroup>
                                </SelectContent>
                            </Select>
                        </div>

                        <Button
                            type="submit"
                            className="px-6 py-2 text-white rounded-md"
                            disabled={isSearching}
                        >
                            {isSearching ? (
                                <>
                                    <Loader2Icon className="animate-spin" />
                                    creating...
                                </>
                            ) : t('button')}
                        </Button>
                    </div>
                </div>
            </form>
        </div>
    )
}